angular.module('HTRD_AutoConsole.A').factory('BaseServ', ['$rootScope', '$window', '$http', '$q',
  function($rootScope, $window, $http, $q) {

    $rootScope.apiRoot = 'http://106.38.67.196:8001';

    return {
      query: function(params) {
        var deferred = $q.defer();
        var token = $window.localStorage.getItem('token');
        var ajaxConfig;

        // 读本地JSON请求
        if (params.Serv) {

          if (!!(params.param && params.param['id'])) {

            // 替换 id占位符
            params.url = params.url.replace('{id}', params.param.id);
          } else {
            params.url = params.url.replace('{id}', '');
          };

          ajaxConfig = {
            method: params.method,
            url: ($rootScope.apiRoot || '') + params.url,
            params: params.param,
            beforeSend: function(request) {
              request.setRequestHeader('token', token);
            }
          };

          var formData = {};

          if (params.method !== 'GET') {

            if (params.method === 'PUT'){
              formData = $.param(params.param);
              ajaxConfig.data = formData;
              delete ajaxConfig.params;
            } else {
              formData = $.param(params.param);
              ajaxConfig.data = formData;
            }
          }
          else {
            formData = params.param;
            ajaxConfig.params = formData;
          };

          $http(ajaxConfig).success(function (ret) {
            deferred.resolve(ret);
          }).error(function (ret) {
            deferred.reject(ret);
          });
        } else {
          $.getJSON('/src/' + params.url, params.param)
            .done(function (ret) {
              deferred.resolve(ret);
            })
            .fail(function (ret) {
              deferred.reject(ret);
            })
        };

        return deferred.promise;
      }
    }
  }
]);

/**
 * Created by Administrator on 2017/4/7.
 */
angular.module('HTRD_AutoConsole.A')
	.factory('HomeServ', ['BaseServ', function(BaseServ) {
		var that = {};
 
		//今日待执行
		var getWaitRun = function(params) {
			var promise = BaseServ.query({
				Serv: false,
				param: params,
				method: 'GET',
				url: 'script/json/SystemWait.json'
			});
			return promise;
		};

		//执行中
		var getRuning = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/exec/running/'
			});
			return promise;
		};

		//执行告警
		var getWarnRun = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				/*url: 'script/json/SystemWarn.json'*/
				url: '/alarm/today/'
			});
			return promise;
		};

		//已结束
		var getEndRun= function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/exec/completed/'
			});
			return promise;
		};

		//执行成功
		var getSuccessRun = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/exec/succeed/'
			});
			return promise;
		};

		//手工接管
		var getHandOver = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/exec/tack_over/'
			});
			return promise;
		};


		that.getWaitRun = getWaitRun;
		that.getRuning = getRuning;
		that.getWarnRun = getWarnRun;
		that.getEndRun = getEndRun;
		that.getSuccessRun = getSuccessRun;
		that.getHandOver = getHandOver;
		return that;
	}]);

angular.module('HTRD_AutoConsole.A')
  .factory('OperationLogServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var getLog = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/OperationLog.json'
      });
      return promise;
    };
    var getUser = function(params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/OperationUser.json'
      });
      return promise;
    };

    that.getLog = getLog;
    that.getUser = getUser;

    return that;
  }]);

angular.module('HTRD_AutoConsole.A')
.factory('ManagerControlServ', ['BaseServ', function(BaseServ) {
  var that = {};

  var getManagerControlList = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      url: '/cron/'
    });
    return promise;
  };

  var getManagerControlInfo = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      url: '/cron/{id}/'
    });
    return promise;
  };

  var addManagerControlInfo = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'POST',
      url: '/cron/'
    });
    return promise;
  };

  var editManagerControlInfo = function(params){
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'PUT',
      url: '/cron/{id}/'
    });
    return promise;
  };

/*  var putEditManagerControlInfo = function(params,id){
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'PUT',
      url: '/cron/'+id+'/'
    });
    return promise;
  };*/



  var delManagerControlInfo = function() {
    var promise = BaseServ.query({
      Serv: false,
      param: params,
      method: 'GET',
      url: 'script/json/ManagerProcessList.json'
    });
    return promise;
  };


  that.getManagerControlList = getManagerControlList;
  that.getManagerControlInfo = getManagerControlInfo;
  that.addManagerControlInfo = addManagerControlInfo;
  that.editManagerControlInfo = editManagerControlInfo;
  //that.putEditManagerControlInfo = putEditManagerControlInfo;
  that.delManagerControlInfo = delManagerControlInfo;
  return that;
}]);

angular.module('HTRD_AutoConsole.A').factory('ManagerHolidayServ', ['BaseServ', function (BaseServ) {
  var that = {};

  var getHolidayList = function (params) {
      var promise = BaseServ.query({
          Serv: true,
          param: params,
          method: 'GET',
          url: '/holiday/'
      });
      return promise;
  };

  var getHolidayInfo = function (params) {
      var promise = BaseServ.query({
          Serv: true,
          param: params,
          method: 'GET',
          url: '/holiday/{id}/'
      });
      return promise;
  };

  var addHolidayInfo = function (params) {
      var promise = BaseServ.query({
          Serv: true,
          param: params,
          method: 'POST',
          url: '/holiday/'
      });
      return promise;
  };

  var editHolidayInfo = function (params) {
      var promise = BaseServ.query({
          Serv: true,
          param: params,
          method: 'PUT',
          url: '/holiday/{id}/'
      });
      return promise;
  };

  var delHolidayInfo = function (params) {
      var promise = BaseServ.query({
          Serv: true,
          param: params,
          method: 'DELETE',
          url: '/holiday/{id}/'
      });
      return promise;
  };

  that.getHolidayList = getHolidayList;
  that.getHolidayInfo = getHolidayInfo;
  that.addHolidayInfo = addHolidayInfo;
  that.editHolidayInfo = editHolidayInfo;
  that.delHolidayInfo = delHolidayInfo;
  return that;
}]);

angular.module('HTRD_AutoConsole.A')
  .factory('ManagerListServ', ['BaseServ', function(BaseServ) {
    var that = {};

    var getProcessList = function(params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        url: '/pipeline/'
      });
      return promise;
    };
    var breadcrumbsData = [
      {
        'iconClass': 'htrd-icon-process-sm',
        'text': '流程管理',
        'link': 'console.base.manager.list'
      },
      {
        'text': '流程列表'
      }
    ];
    /*var headList = [
      {
        'title': '序号',
        'type': 'ignore'
      },
      {
        'title': '流程状态',
        'type': 'ignore'
      },
      {
        'title': '流程名称',
        'type': 'ignore'
      },
      {
        'title': '分类',
        'type': 'ignore'
      },
      {
        'title': '节点数',
        'type': 'ignore'
      },
      {
        'title': '创建人',
        'type': 'ignore'
      },
      {
        'title': '修改人',
        'type': 'ignore'
      },
      {
        'title': '创建时间',
        'type': 'created_at'
      },
      // {
      //   'title': '审核人',
      //   'type': 'reviewer'
      // },
      // {
      //   'title': '审批时间',
      //   'type': 'reviewed_at'
      // },
      // {
      //   'title': '审核状态',
      //   'type': 'ignore'
      // },
      {
        'title': '操作',
        'type': 'ignore'
      }
    ];*/

    var stateOptions = [
      {
        'title': '全部状态'
      },

      {
        'id': 0,
        'title': '未执行'
      },
      {
        'id': 1,
        'title': '正在检测'
      },
      {
        'id': 2,
        'title': '执行中'
      }
    ];
    var stateParse = function(state) {
      var stateObj = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      };
      return stateObj[state];
    };

    that.breadcrumbsData = breadcrumbsData;
    //that.headList = headList;
    that.stateOptions = stateOptions;
    that.stateParse = stateParse;
    that.getProcessList = getProcessList;
    return that;
  }]);

angular.module("HTRD_AutoConsole.A").factory('ManagerProcessQuneeServ', ['BaseServ', function (BaseServ) {
  var that = {};

  // 模拟取node json
  var getNodeJsonTest = function(params) {
    var promise = BaseServ.query({
      Serv: false,
      param: params,
      method: 'GET',
      url: 'script/json/NodeJsonTest.json'
    });
    return promise;
  }

  // 获取当前流程属性
  var getManagerProcessQuneeInfo = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeInfo.json'
      url: '/pipeline/{id}/info/'
    });
    return promise;
  };

  // 获取当前流程节点属性
  var getManagerProcessQuneeNodeInfo = function(params) {
    var promise = BaseServ.query({
      Serv: false,
      param: params,
      method: 'GET',
      url: 'script/json/ManagerProcessQuneeNodeInfo.json'
    });
    return promise;
  };

  // 获取流程日志
  var getManagerProcessQuneeLogList = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeLogList.json'
      url: '/exec/{id}/log/'
    });
    return promise;
  };

  // 获取用户列表
  var getUserList = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/UserList.json'
      url: '/users/'
    });
    return promise;
  };

  // 流程 - 用户提交确认节点
  var submitManagerProcessQuneeUserConfirm = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      url: '/exec/{id}/affirm/'
      // url: 'script/json/ManagerProcessQuneeUserConfirm.json'
    });
    return promise;
  };


  // 流程 - 获取用户所有状态字典
  var getManagerProcessQuneeStateMap = function(params) {
    var promise = BaseServ.query({
      Serv: false,
      param: params,
      method: 'GET',
      url: 'script/json/ManagerProcessQuneeStateMap.json'
    });
    return promise;
  };

  // 获取当前流程状态及节点数据
  var getManagerProcessQuneeStateAndData = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeState.json'
      url: '/pipeline/{id}/'
    });
    return promise;
  };

  // 获取执行中具体状态及节点
  var getManagerProcessQuneeExecState = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeExecState.json'
      // url: '/pipeline/{id}/status/'
      url: '/exec/{id}/'
    });
    return promise;
  };

  // 流程图事件

  // 检测当前流程
  var ManagerProcessQuneeCheck = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeCheck.json'
      url: '/pipeline/{id}/check/'
    });
    return promise;
  };

  // 开始执行当前流程
  var ManagerProcessQuneeStart = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeStart.json'
      url: '/pipeline/{id}/run/'
    });
    return promise;
  };

  // 暂停执行当前流程
  var ManagerProcessQuneePause = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneePause.json'
      url: '/exec/{id}/pause/'
    });
    return promise;
  };

  // 继续执行当前流程
  var ManagerProcessQuneeContinue = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeContinue.json'
      url: '/exec/{id}/goon/'
    });
    return promise;
  };

  // 终止执行当前流程
  var ManagerProcessQuneeQuit = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeQuit.json'
      url: '/exec/{id}/stop/'
    });
    return promise;
  };

  // 重做该节点
  var ManagerProcessQuneeResetNode = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeResetNode.json'
      url: '/exec/{id}/redo/'
    });
    return promise;
  };

  // 手工接管
  var ManagerProcessQuneeManualNozzleNode = function (params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeManualNozzleNode.json'
      url: '/exec/{id}/take/'
    });
    return promise;
  };

  // 获取历史执行流程
  var getManagerProcessQuneeHistoryList = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      // url: 'script/json/ManagerProcessQuneeHistoryList.json'
      url: '/pipeline/{id}/history/'
    });
    return promise;
  };

  that.getNodeJsonTest = getNodeJsonTest;
  that.getManagerProcessQuneeNodeInfo = getManagerProcessQuneeNodeInfo;
  that.ManagerProcessQuneeResetNode = ManagerProcessQuneeResetNode;
  that.getManagerProcessQuneeInfo = getManagerProcessQuneeInfo;
  that.getManagerProcessQuneeLogList = getManagerProcessQuneeLogList;
  that.getUserList = getUserList;
  that.submitManagerProcessQuneeUserConfirm = submitManagerProcessQuneeUserConfirm;
  that.getManagerProcessQuneeStateMap = getManagerProcessQuneeStateMap;
  that.getManagerProcessQuneeExecState = getManagerProcessQuneeExecState;
  that.getManagerProcessQuneeStateAndData = getManagerProcessQuneeStateAndData;
  that.ManagerProcessQuneeCheck = ManagerProcessQuneeCheck;
  that.ManagerProcessQuneeStart = ManagerProcessQuneeStart;
  that.ManagerProcessQuneePause = ManagerProcessQuneePause;
  that.ManagerProcessQuneeContinue = ManagerProcessQuneeContinue;
  that.ManagerProcessQuneeQuit = ManagerProcessQuneeQuit;
  // that.ManagerProcessQuneeOnlyExecuteSelfNode = ManagerProcessQuneeOnlyExecuteSelfNode;
  // that.ManagerProcessQuneeSkipSelfNode = ManagerProcessQuneeSkipSelfNode;
  that.ManagerProcessQuneeManualNozzleNode = ManagerProcessQuneeManualNozzleNode;
  that.getManagerProcessQuneeHistoryList = getManagerProcessQuneeHistoryList;
  return that;
}])

angular.module('HTRD_AutoConsole.A')
.factory('ManagerProcessServ', ['BaseServ', function(BaseServ) {
  var that = {};

  var getNodeInfo = function(params) {
    var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        // url: 'script/json/ManagerNodeInfo.json'
        url: '/node/{id}/'
    });
    return promise;
  };


  var getNodeChartByCPU = function(params) {
    var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/ManagerNodeChartByCPU.json'
    });
    return promise;
  };

  var getNodeChartByMemory = function(params) {
    var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/ManagerNodeChartByMemory.json'
    });
    return promise;
  };

  that.getNodeInfo = getNodeInfo;
  that.getNodeChartByCPU = getNodeChartByCPU;
  that.getNodeChartByMemory = getNodeChartByMemory;
  return that;
}]);

angular.module("HTRD_AutoConsole.A").factory('ManagerProcessTreeServ', ['BaseServ', function(BaseServ) {
  var that = {};
  // 临时记录id,防止重复(正式环境去掉)
  // var id = 1;

  // 获取整个流程树
  var getProcessTree = function(params) {
    // var promise = BaseServ.query({
    //   Serv: false,
    //   param: params,
    //   method: 'GET',
    //   url: 'script/json/ManagerTreeData.json'
    // });
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      url: '/groups/'
    });
    return promise;
  };
  // 获取某个流程节点
  var getProcessTreeById = function(params) {
    var promise = BaseServ.query({
      Serv: true,
      param: params,
      method: 'GET',
      url: '/groups/{id}/'
    });
    return promise;
  };


  // 后端数据返回的name属性递归改为text属性
  // 设置分类disabled，流程icon
  var setTreeData = function(data) {
    var copyData = JSON.parse(JSON.stringify(data));

    // 假id,防止重复(正式环境去掉)
    // copyData.id = id ++;

    copyData.text = copyData.name;
    delete copyData.name;

    // 分类
    if (copyData.children && copyData.children.length) {

      // 设置禁用
      // if (copyData.state) {
      //   copyData.state.disabled = true;
      // } else {
      //   copyData.state = {
      //     'disabled': true
      //   }
      // }

      if (typeof copyData.children[0] === 'number') {
        copyData.li_attr = {
          'notload': 'true'
        };
        copyData.children = [true];
        return copyData;
      }

      // 递归设置
      copyData.children = copyData.children.map(function(item) {
        return setTreeData(item);
      });
    } else {
      // 流程
      // copyData.icon = 'https://www.jstree.com/tree-icon.png';
    }

    return copyData;
  };

  // 获取流程状态列表
  // var getProcessState = function(params) {
  //   var promise = BaseServ.query({
  //     Serv: false,
  //     param: params,
  //     method: 'GET',
  //     url: 'script/json/ManagerProcessState.json'
  //   });
  //   return promise;
  // };

  that.getProcessTree = getProcessTree;
  that.getProcessTreeById = getProcessTreeById;
  // that.getProcessState = getProcessState;
  that.setTreeData = setTreeData;

  return that;
}])

angular.module('HTRD_AutoConsole.A')
  .factory('ManagerResultServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var headList = [
      {
        'title': '序号',
        'type': 'ignore'
      },
      {
        'title': '开始时间',
        'type': 'started_at'
      },
      {
        'title': '结束时间',
        'type': 'ended_at'
      },
      {
        'title': '流程名称',
        'type': 'ignore'
      },
      {
        'title': '分类',
        'type': 'ignore'
      },
      {
        'title': '节点数',
        'type': 'ignore'
      },
      {
        'title': '执行结果',
        'type': 'ignore'
      },
      {
        'title': '备注',
        'type': 'ignore'
      },
      {
        'title': '执行人',
        'type': 'ignore'
      }
    ];
    var resultOptions = [
      {
        'title': '全部结果'
      },
      {
        'id': '9',
        'title': '执行成功'
      },
      {
        'id': '19',
        'title': '被不认可终止'
      },
      {
        'id': '21',
        'title': '手工接管后的执行结果：成功'
      },
      {
        'id': '22',
        'title': '手工接管后的执行结果：失败'
      },
      {
        'id': '20',
        'title': '执行完成但有错误'
      },

      {
        'id': '2',
        'title': '检测异常'
      }
    ];

    var getResult = function (params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        url: '/exec/'
      });
      return promise;
    };

    that.headList = headList;
    that.resultOptions = resultOptions;
    that.getResult = getResult;
    return that;
  }]);

angular.module('HTRD_AutoConsole.A').factory('ManagerReviewServ', ['BaseServ', function(BaseServ) {
  var that = {};

  var breadcrumbsData = [
    {
      'iconClass': 'icon-home',
      'text': '流程管理',
      'link': 'console.base.manager.list'
    },
    {
      'text': '流程审核'
    }
  ];
  var headList = [
    {
      'title': '序号',
      'type': 'ignore'
    },
    {
      'title': '流程名称',
      'type': 'name'
    },
    {
      'title': '分类',
      'type': 'ignore'
    },
    {
      'title': '节点数',
      'type': 'node_count'
    },
    {
      'title': '创建人',
      'type': 'creator_name'
    },
    {
      'title': '修改人',
      'type': 'modifier_name'
    },
    {
      'title': '编辑时间',
      'type': 'editTime'
    },
    {
      'title': '审核人',
      'type': 'reviewer_name'
    },
    {
      'title': '审批时间',
      'type': 'reviewerTime'
    },
    {
      'title': '审批状态',
      'type': 'ignore'
    },
    {
      'title': '操作',
      'type': 'ignore'
    }
  ];
  var stateParse = {
    pending: '待审批',
    passed: '已通过',
    rejected: '已拒绝'
  };
  var getReviewList = function(params) {
    var promise = BaseServ.query({
      Serv: false,
      param: params,
      method: 'GET',
      url: 'script/json/ManagerReviewList.json'
    });
    return promise;
  };

  that.breadcrumbsData = breadcrumbsData;
  that.headList = headList;
  that.stateParse = stateParse;
  that.getReviewList = getReviewList;

  return that;
}]);
angular.module('HTRD_AutoConsole.A')
  .factory('ManagerWarnServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var getResult = function (params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        /*url: 'script/json/ManagerProcessWarn.json'*/
        url: '/alarm/'
      });
      return promise;
    };

    that.getResult = getResult;
    return that;
  }]);

angular.module('HTRD_AutoConsole.A')
  .factory('addGroupManagementServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var getUserList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/UserGroupsAllList.json'
      });
      return promise;
    };

    var getPermissionList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/UserPermissionAllList.json'
      });
      return promise;
    };

    var getGroupInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/AddUserManagement.json'
        //url: '/users/{id}/'
      });
      return promise;
    };

    //添加用户保存
    var getSaveGroupInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'POST',
        url: 'script/json/AddUserManagement.json'
      });
      return promise;
    };

//编辑用户保存
    var getEditGroupInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'PUT',
        url: 'script/json/AddUserManagement.json'
      });
      return promise;
    };

    that.getPermissionList = getPermissionList;
    that.getUserList = getUserList;
    that.getGroupInfo = getGroupInfo;
    that.getSaveGroupInfo = getSaveGroupInfo;
    that.getEditGroupInfo = getEditGroupInfo
    return that;
  }]);
angular.module('HTRD_AutoConsole.A')
  .factory('addUserManagementServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var getGroupList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/UserGroupsAllList.json'
      });
      return promise;
    };

    var getUserInfo = function (params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        url: '/users/{id}/'
      });
      return promise;
    };

    // 添加用户保存
    var saveUserInfo = function (params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'POST',
        url: '/users/'
      });
      return promise;
    };

    //编辑用户保存
    var editUserInfo = function (params) {
      console.log(params)
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'PUT',
        url: '/users/{id}/'
        /*url: 'script/json/AddUserManagement.json'*/
      });
      return promise;
    };

    that.getGroupList = getGroupList;
    that.getUserInfo = getUserInfo;
    that.saveUserInfo = saveUserInfo;
    that.editUserInfo = editUserInfo
    return that;
  }]);

angular.module('HTRD_AutoConsole.A')
  .factory('GroupManagementServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var getGroupManagement = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/GroupManagement.json'
      });
      return promise;
    };

    that.getGroupManagement = getGroupManagement;
    return that;
  }]);
angular.module('HTRD_AutoConsole.A')
  .factory('UserManagementServ', ['BaseServ', function (BaseServ) {
    var that = {};

    //得到用户列表
    var getUserManagement = function (params) {
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'GET',
        url: '/users/'
        /*url: 'script/json/UserManagement.json'*/
      });
      return promise;
    };

    //修改密码
    var getChangePassword= function (params) {
      console.log(params);
      var promise = BaseServ.query({
        Serv: true,
        param: params,
        method: 'POST',
        url: '/users/{id}/password_change/'
      });
      return promise;
    };

    that.getUserManagement = getUserManagement;
    that.getChangePassword = getChangePassword;
    return that;
  }]);
angular.module('HTRD_AutoConsole.A')
  .factory('processEditServ', ['BaseServ', function (BaseServ) {
    var that = {};

    var saveProcessInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: ''
      });
      return promise;
    };

    var saveNodeInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: ''
      });
      return promise;
    };
    
    var getMachineList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/ManagerTreeData.json'
      });
      return promise;
    };

    var getScriptList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/ManagerTreeData.json'
      });
      return promise;
    };

    var getUserList = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: ' '
      });
      return promise;
    };

    var getProcessList = function(params){
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/ManagerTreeData.json'
      });
      return promise;
    };

    var getNodeInfo = function (params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: ' '
      });
      return promise;
    };

    that.getMachineList = getMachineList;
    that.getScriptList = getScriptList;
    that.getUserList = getUserList;
    that.getProcessList = getProcessList;
    that.getNodeInfo = getNodeInfo;
    that.saveProcessInfo = saveProcessInfo;
    that.saveNodeInfo = saveNodeInfo;
    return that;
  }]);

angular.module("HTRD_AutoConsole.A").factory('LoginServ', ['BaseServ', function(BaseServ) {
  var that = {};

  // 登录系统
  var checkUserLoginFrom = function(params) {
    return BaseServ.query({
      Serv: true,
      method: 'POST',
      params: params,
      //method: 'GET',
      url: 'login',
      
    });
  };

  that.checkUserLoginFrom = checkUserLoginFrom;
  return that;
}])

/**
 * Created by Administrator on 2017/4/16.
 */
angular.module('HTRD_AutoConsole.A')
	.factory('MessagePanelServ', ['BaseServ', function(BaseServ) {
		var that = {};

		var getManagerInfo = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/notice/'
			});
			return promise;
		};

		var getManagerOperation = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/notice/{id}/status/'
			});
			return promise;
		};

		var getManagerClean = function(params) {
			var promise = BaseServ.query({
				Serv: true,
				param: params,
				method: 'GET',
				url: '/notice/clean/'
			});
			return promise;
		};

		that.getManagerInfo = getManagerInfo;
		that.getManagerOperation = getManagerOperation;
		that.getManagerClean = getManagerClean;
		return that;
	}]);

angular.module('HTRD_AutoConsole.A')
  .factory('UserInfoServ', ['BaseServ', function(BaseServ) {
    var that = {};

    var getUserInfo = function(params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'GET',
        url: 'script/json/userInfo.json'
      });
      return promise;
    };

    var getNewUserInfo = function(params) {
      var promise = BaseServ.query({
        Serv: false,
        param: params,
        method: 'PUT',
        url: 'script/json/userInfo.json'
      });
      return promise;
    };

    that.getUserInfo = getUserInfo;
    that.getNewUserInfo = getNewUserInfo;
    return that;
  }]);

// alert
angular.module("HTRD_AutoConsole.A").factory('AlertServ', ['DialogServ', function(DialogServ) {
      var that = {};

      var showAlert = function(title, type) {
        DialogServ.alert({
          'animation': 'am-fade-and-slide-top',
          'placement': 'top',
          'duration': 2,
          'title': title,
          'type': type
        });
      };

      var showSuccess = function(content) {
        showAlert(content || '执行成功', 'success');
      };

      var showWarning = function(content) {
        showAlert(content || '执行警告', 'warning');
      };

      var showError = function(content) {
        showAlert(content || '执行错误', 'danger');
      };

      that.showSuccess = showSuccess;
      that.showWarning = showWarning;
      that.showError = showError;
      return that;
    }
])

// 格式化时间
angular.module("HTRD_AutoConsole.A").factory('DateParseServ', [function() {
  var result;
  var that = {};

  // '2017-04-28T03:20:06.003405Z' -> '2017-04-28 03:20:06'
  var parseStr = function(str) {

    if (str.indexOf('.') !== -1) {
      str = str.split('.')[0];
    };
    str = str.replace('T', ' ').replace('Z', ' ');
    return str;
  };

  var dateParse = function(date) {

    if (typeof date === 'string') {
      result = parseStr(date);
    }

    else if (Array.isArray(date)) {
      result = [];
      date.map(function(item, index) {
        result.push(parseStr(item));
      });
    };

    return result;
  };

  that.dateParse = dateParse;
  return that;
}])

// dialog服务
angular.module("HTRD_AutoConsole.A").factory('DialogServ', ['$modal', '$alert', '$aside',
    function($modal, $alert, $aside) {
        var tmpObj = {},
            tmpDialogObj,
            // 脚手架
            bootstrap = function(constructor, options) {
                tmpDialogObj = constructor(options);

                tmpObj.list.push(tmpDialogObj);

                return tmpDialogObj;
            },
            // 处理列表
            dealList = function(funcName) {
                for (var i = 0,
                        listLen = tmpObj.list.length,
                        item; i < listLen; i++) {
                    item = tmpObj.list[i];

                    if (item.hasOwnProperty(funcName) && angular.isFunction(item[funcName])) {
                        item[funcName]();

                        // 移除list
                        if (funcName == 'destroy') {
                            // 删除当前项
                            tmpObj.list.splice(i, 1);
                            listLen = tmpObj.list.length;
                            i--;
                        }
                    }
                }
            };

        // list
        tmpObj.list = [];

        tmpObj.modal = function(options) {

          // 设置默认值
          options.animation = options.animation || 'am-fade-and-scale';
          options.backdrop = options.backdrop || 'static';
          return bootstrap($modal, options);
        };

        tmpObj.alert = function(options) {
          return bootstrap($alert, options);
        };

        tmpObj.aside = function(options) {
          return bootstrap($aside, options);
        };

        // hide
        tmpObj.hide = function(callback) {
          dealList('hide');
          callback && callback();
        };
        // destroy
        tmpObj.destroy = function() {
          dealList('destroy');
        };

        return tmpObj;
    }
])

//浏览器消息通知
angular.module("HTRD_AutoConsole.A").factory('NotificationServ', ['$window', function($window) {

	var that = {};
	var init;

	var selfData;
	var selfCallback;

	// 初始化
	var init = function(data, callback) {
		selfData = data;
		selfCallback = callback;
		console.log('浏览器弹窗')
		var notification = new Notification(data.title + ":", {
			dir: "auto",
			lang: "hi",
			tag: " ",
			icon:'img/logo.png',
			body: data.result_info  + data.created_at
		});

		notification.onclick = function (evt) {
			selfCallback(selfData);
		};
	};


	that.init = init;
	return that;
}]);

// 操作本地缓存字典数据
angular.module("HTRD_AutoConsole.A").factory('ParseMapServ', ['$window', function($window) {
  var that = {};

  var setItem = function(key, value, mapName) {
    var map = JSON.parse($window.localStorage.getItem(mapName)) || {};
    map[key] = value;
    $window.localStorage.setItem(mapName, JSON.stringify(map));
  };

  var getItem = function(key, mapName) {
    var map = JSON.parse($window.localStorage.getItem(mapName)) || {};
    return map[key];
  };

  var removeItem = function(key, mapName) {
    var map = JSON.parse($window.localStorage.getItem(mapName)) || {};
    delete map[key];
    $window.localStorage.setItem(mapName, JSON.stringify(map));
  };

  that.setItem = setItem;
  that.getItem = getItem;
  that.removeItem = removeItem;
  return that;
}])

// socket长链接
angular.module("HTRD_AutoConsole.A").factory('SocketServ', ['$window', function($window) {

  var that = {};
  var webSocketBridge;
  var socketUrl;
  var token = $window.localStorage.getItem('token');

  // 初始化
  var initSocket = function(id) {
     socketUrl = 'ws://106.38.67.196:8001/chat/' + id + '?token=' + token;
     webSocketBridge = new $window.channels.WebSocketBridge();
     webSocketBridge.connect(socketUrl);
     console.log('webSocketBridge', webSocketBridge);
  };

  // 接收消息
  var onMessage = function(callback) {
    webSocketBridge.listen(function(action, stream) {
      callback && callback(action);
    });
  };

  var onClose = function() {
    webSocketBridge.socket.onclose = function() {
      console.log('webSocketBridge.onClose')
    }
  }

  var onError = function() {
    webSocketBridge.socket.onerror = function() {
      console.log('webSocketBridge.onError')
    }
  }

  // 发送消息
  var sendMessage = function(data) {
    webSocketBridge.send({
      token: token,
      data: data
    });
  };

  // 断开连接
  var closeSocket = function() {
    webSocketBridge.socket.close();
  };

  that.initSocket = initSocket;
  that.onMessage = onMessage;
  that.sendMessage = sendMessage;
  that.closeSocket = closeSocket;
  that.onClose = onClose;
  that.onError = onError;
  return that;
}])


// 1. conncat
// 2. 断网
// 3. sent 心跳
// 4. 等待超时 ()
// 5. onclose && onerror

// 状态对应文本
angular.module('HTRD_AutoConsole.A').factory('StatusMapServ', [function() {
  var result;

  var that = {};

   var statusMap = {
      2: {
        text: '检测异常'
      },
      19:{
        text: '被不认可终止'
      },
      20:{
        text: '执行完成但有错误'
      },
      21:{
        text: '手工接管后的执行结果：成功'
      },
      22:{
        text: '手工接管后的执行结果：失败'
      },
      6:{
        text: '执行中'
      },
      7:{
        text: '执行失败'
      },
      8:{
        text: '执行超时'
      },
      9:{
        text: '执行成功'
      },
      11:{
        text: '手工终止'
      },
      13:{
        text: '暂停'
      }
  };

  var getStatusData = function(statusIndex) {
    result =  statusMap[statusIndex];
    return result;
  };

  that.getStatusData = getStatusData;
  return that;
}])
